# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

class Coperativa(db.Model):
  name = db.StringProperty(required=True)
  direction = db.TextProperty()
  
  def __str__(self):
      return '%s' %self.name
  
class UsuariCoperativa(db.Model):
  usuari = db.UserProperty()
  coperativa = db.Reference(Coperativa)
  
class Productor(db.Model):
  name = db.StringProperty(required=True)
  description = db.TextProperty()
  contact = db.TextProperty()

  def __str__(self):
      return '%s' %self.name



class Product(db.Model):
  name = db.StringProperty(required=True)
  foto = db.BlobProperty(default=None)
  description = db.TextProperty()
  price = db.FloatProperty(default=0.0)
  actiu = db.BooleanProperty(default=False)
  productor = db.Reference(Productor)
  coperativa = db.Reference(Coperativa)
  owner = db.UserProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)

  def __str__(self):
      return '%s' %self.name



class Compra(db.Model):
  usuari = db.UserProperty()
  quantitat = db.FloatProperty(default=0.0)
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
  product = db.Reference(Product)
  historica = db.BooleanProperty(default=False)
  coperativa = db.Reference(Coperativa)
  perquan = db.DateTimeProperty()
  preualcomprar = db.FloatProperty()

class UsuariCoperativaForm(djangoforms.ModelForm):
  class Meta:
    model = UsuariCoperativa

class CoperativaForm(djangoforms.ModelForm):
  class Meta:
    model = Coperativa

class CompraForm(djangoforms.ModelForm):
  class Meta:
    model = Compra
    exclude = ['coperativa','created','modified','usuari']
    

class ProductorForm(djangoforms.ModelForm):
  class Meta:
    model = Productor

from django.http import HttpResponsePermanentRedirect
from google.appengine.api import users

def loginrequired(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user:
            return func(request, *args, **kw)
        else:
            return http.HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    return _wrapper

managers = ('ramon.nb@gmail.com',)

def managerrequired(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user.email() in managers:
            return func(request, *args, **kw)
        else:
            return http.HttpResponseRedirect("/")
            
    return _wrapper
            

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.CreateLogoutURL('/')
    params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)

@loginrequired
def index(request):
  """Request / -- show all gifts."""
  user = users.GetCurrentUser()
  
  coperatives_usuari = db.GqlQuery('SELECT * FROM UsuariCoperativa WHERE usuari=:1', user)
  coperatives = []
  for cope_user in coperatives_usuari:
      cope = cope_user.coperativa
      coperatives.append(cope)
  productors = db.GqlQuery('SELECT * FROM Productor')
  return respond(request, user, 'list', {'coperatives': coperatives, 'productors': productors})

